package com.cs307.redcross.client;

import java.io.Serializable;
import java.util.Vector;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ChangeEvent;

public class ErrorLogsContent extends Content implements Serializable {
	private static final long serialVersionUID = -1189011235559691201L;
	private DatabaseHandlerServiceAsync databaseHandlerService = (DatabaseHandlerServiceAsync) GWT.create(DatabaseHandlerService.class);
	private final String relogString = "If this problem persists try relogging into the system.";
	
	Vector<LogFileEntry> logFiles = new Vector<LogFileEntry>();
	
	// UI Widgets
	ListBox logEntryListBox;
	TextArea messageTextBox;
	
	public ErrorLogsContent() {
		
		databaseHandlerService.getAllLogFileEntries(new AsyncCallback<Vector<LogFileEntry>>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Error: Unable to retrieve logs from the server." + relogString);
			}

			@Override
			public void onSuccess(Vector<LogFileEntry> result) {	
				if (result != null && !result.isEmpty()) {
					for (LogFileEntry lfe : result) {
						if (lfe == null || !lfe.isDeveloperOnly())
							continue;
						
						logFiles.add(lfe);
						logEntryListBox.addItem(lfe.getTime().toString());
					}
				}
			}
		});
		
		AbsolutePanel absolutePanel = new AbsolutePanel();
		initWidget(absolutePanel);
		absolutePanel.setSize("1121px", "653px");
		
		Label lblSelectEvent = new Label("Log Entries:");
		absolutePanel.add(lblSelectEvent, 10, 10);
		
		messageTextBox = new TextArea();
		absolutePanel.add(messageTextBox, 319, 34);
		messageTextBox.setSize("748px", "560px");
		
		Label lblEventDescription = new Label("Log Message:");
		absolutePanel.add(lblEventDescription, 319, 10);
		lblEventDescription.setSize("122px", "18px");
		
		logEntryListBox = new ListBox();
		logEntryListBox.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				populateForm();
			}
		});
		logEntryListBox.setVisibleItemCount(30);
		absolutePanel.add(logEntryListBox, 10, 34);
		logEntryListBox.setSize("259px", "564px");	
		messageTextBox.setEnabled(false);
	}
	
	private void populateForm() {
		if (logEntryListBox.getSelectedIndex() != -1) {
			LogFileEntry lfe = logFiles.get(logEntryListBox.getSelectedIndex());
			
			if (lfe != null) {
				messageTextBox.setText(lfe.getLogAction());
			}
		}
	}
}
